package com.example.myapplicationktkt2.sqlite

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplicationktkt2.R
import com.example.myapplicationktkt2.database.UserDao
import com.example.myapplicationktkt2.model.User

/**
 * SQLite数据库增删改查演示Activity
 * 演示了SQLite数据库的基本操作：增加、删除、修改、查询
 */
class SQLiteDemoActivity : AppCompatActivity() {

    // 数据库访问对象
    private lateinit var userDao: UserDao

    // UI组件
    private lateinit var etName: EditText
    private lateinit var etEmail: EditText
    private lateinit var btnAdd: Button

    private lateinit var etUpdateId: EditText
    private lateinit var etUpdateName: EditText
    private lateinit var etUpdateEmail: EditText
    private lateinit var btnUpdate: Button

    private lateinit var etDeleteId: EditText
    private lateinit var btnDelete: Button

    private lateinit var btnQueryAll: Button
    private lateinit var etQueryId: EditText
    private lateinit var btnQueryById: Button

    private lateinit var tvResult: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sqlite_demo)

        // 初始化数据库访问对象
            userDao = UserDao.Companion.getInstance(this)

        // 初始化UI组件
        initViews()

        // 设置点击事件
        setClickListeners()
    }

    /**
     * 初始化UI组件
     */
    private fun initViews() {
        // 添加数据相关组件
        etName = findViewById(R.id.etName)
        etEmail = findViewById(R.id.etEmail)
        btnAdd = findViewById(R.id.btnAdd)

        // 更新数据相关组件
        etUpdateId = findViewById(R.id.etUpdateId)
        etUpdateName = findViewById(R.id.etUpdateName)
        etUpdateEmail = findViewById(R.id.etUpdateEmail)
        btnUpdate = findViewById(R.id.btnUpdate)

        // 删除数据相关组件
        etDeleteId = findViewById(R.id.etDeleteId)
        btnDelete = findViewById(R.id.btnDelete)

        // 查询数据相关组件
        btnQueryAll = findViewById(R.id.btnQueryAll)
        etQueryId = findViewById(R.id.etQueryId)
        btnQueryById = findViewById(R.id.btnQueryById)

        // 结果显示组件
        tvResult = findViewById(R.id.tvResult)
    }

    /**
     * 设置点击事件监听器
     */
    private fun setClickListeners() {
        // 添加记录按钮点击事件
        btnAdd.setOnClickListener {
            addUser()
        }

        // 更新记录按钮点击事件
        btnUpdate.setOnClickListener {
            updateUser()
        }

        // 删除记录按钮点击事件
        btnDelete.setOnClickListener {
            deleteUser()
        }

        // 查询所有记录按钮点击事件
        btnQueryAll.setOnClickListener {
            queryAllUsers()
        }

        // 按ID查询按钮点击事件
        btnQueryById.setOnClickListener {
            queryUserById()
        }
    }

    /**
     * 添加用户
     */
    private fun addUser() {
        val name = etName.text.toString().trim()
        val email = etEmail.text.toString().trim()

        // 检查输入是否为空
        if (name.isEmpty() || email.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
            return
        }

        // 创建用户对象
        val user = User(name = name, email = email)

        // 插入数据库
        val newRowId = userDao.insertUser(user)

        if (newRowId != -1L) {
            Toast.makeText(this, "添加成功，ID: $newRowId", Toast.LENGTH_SHORT).show()
            // 清空输入框
            etName.text.clear()
            etEmail.text.clear()
        } else {
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 更新用户
     */
    private fun updateUser() {
        val idStr = etUpdateId.text.toString().trim()
        val name = etUpdateName.text.toString().trim()
        val email = etUpdateEmail.text.toString().trim()

        // 检查输入是否为空
        if (idStr.isEmpty() || name.isEmpty() || email.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
            return
        }

        // 检查ID是否为数字
        val id: Long
        try {
            id = idStr.toLong()
        } catch (e: NumberFormatException) {
            Toast.makeText(this, "ID必须为数字", Toast.LENGTH_SHORT).show()
            return
        }

        // 创建用户对象
        val user = User(name = name, email = email)

        // 更新数据库
        val rowsAffected = userDao.updateUser(id, user)

        if (rowsAffected > 0) {
            Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show()
            // 清空输入框
            etUpdateId.text.clear()
            etUpdateName.text.clear()
            etUpdateEmail.text.clear()
        } else {
            Toast.makeText(this, "更新失败，未找到ID为" + id + "的用户", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 删除用户
     */
    private fun deleteUser() {
        val idStr = etDeleteId.text.toString().trim()

        // 检查输入是否为空
        if (idStr.isEmpty()) {
            Toast.makeText(this, "请输入要删除的用户ID", Toast.LENGTH_SHORT).show()
            return
        }

        // 检查ID是否为数字
        val id: Long
        try {
            id = idStr.toLong()
        } catch (e: NumberFormatException) {
            Toast.makeText(this, "ID必须为数字", Toast.LENGTH_SHORT).show()
            return
        }

        // 删除用户
        val rowsAffected = userDao.deleteUser(id)

        if (rowsAffected > 0) {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
            // 清空输入框
            etDeleteId.text.clear()
        } else {
            Toast.makeText(this, "删除失败，未找到ID为" + id + "的用户", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 查询所有用户
     */
    private fun queryAllUsers() {
        val users = userDao.queryAllUsers()

        if (users.isEmpty()) {
            tvResult.text = "暂无数据"
        } else {
            val result = StringBuilder()
            result.append("共查询到${users.size}条记录:\n\n")
            users.forEach { user ->
                result.append("ID: ${user.id}\n")
                result.append("姓名: ${user.name}\n")
                result.append("邮箱: ${user.email}\n")
                result.append("--------------------\n")
            }
            tvResult.text = result.toString()
        }
    }

    /**
     * 根据ID查询用户
     */
    private fun queryUserById() {
        val idStr = etQueryId.text.toString().trim()

        // 检查输入是否为空
        if (idStr.isEmpty()) {
            Toast.makeText(this, "请输入要查询的用户ID", Toast.LENGTH_SHORT).show()
            return
        }

        // 检查ID是否为数字
        val id: Long
        try {
            id = idStr.toLong()
        } catch (e: NumberFormatException) {
            Toast.makeText(this, "ID必须为数字", Toast.LENGTH_SHORT).show()
            return
        }

        // 查询用户
        val user = userDao.queryUserById(id)

        if (user != null) {
            val result = "ID: ${user.id}\n姓名: ${user.name}\n邮箱: ${user.email}"
            tvResult.text = result
            // 清空输入框
            etQueryId.text.clear()
        } else {
            tvResult.text = "未找到ID为" + id + "的用户"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 关闭数据库连接
        userDao.close()
    }
}